package com.bms.cfcmms;

import com.bms.cfcmms.model.system.authority.Token;
import com.bms.cfcmms.service.authority.RedisTokenService;
import com.github.springtestdbunit.DbUnitTestExecutionListener;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;

/**
 * Created by carlliu on 2016/4/10.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:springMVC-servlet-test.xml"})
@WebAppConfiguration
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        DbUnitTestExecutionListener.class})
public class JunitBase {

    protected MockMvc mockMvc;
    @Autowired
    protected WebApplicationContext wac;

    protected String tokenId;
    @Resource
    private RedisTokenService redisTokenService;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
        //初始化数据库
        Token token = redisTokenService.createToken();
        tokenId = token.getUserId();
    }

    protected MockHttpServletRequestBuilder getHttpRequestBuilder(String path,
                                                                             MultiValueMap<String, String> params) {
        MockHttpServletRequestBuilder mockBuild = post(path).
                accept(MediaType.APPLICATION_JSON);
        if (params != null) {
            mockBuild.params(params);
        }
        mockBuild.header("authorization", this.tokenId);

        return mockBuild;
    }

    protected MockHttpServletRequestBuilder getHttpRequestBuilder(String path) {
        return getHttpRequestBuilder(path, null);
    }
}
